<template>
  <div class="mb-4">
    <el-form :model="form" label-width="auto" style="max-width: 500px">
      <el-form-item label="">
        <el-input
            v-model="form.message"
            placeholder="请输入审批意见"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 8 }"
        />
      </el-form-item>
      <el-form-item class="action-btns" v-loading="loading">
        <el-button type="primary" @click="onApprove('approve')">审批</el-button>
        <el-button type="primary" @click="onApprove('addsign')">加签</el-button>
        <el-button type="primary" @click="onApprove('hold')">暂存</el-button>
        <el-button type="info" @click="onApprove('turn_do')">转办</el-button>
        <el-button type="info" @click="onApprove('claim')">签收</el-button>
        <el-button type="info" @click="onApprove('unClaim')">反签收</el-button>
        <el-button type="info" @click="onApprove('turn_read')">转阅</el-button>
        <el-button type="warning" @click="onApprove('reject')">驳回</el-button>
        <el-button type="danger" @click="onApprove('stop')">终止</el-button>

      </el-form-item>
    </el-form>

    <!-- 审批弹窗 -->
    <el-dialog :title="approveTitle" v-model="approveDialogVisible" width="600px" append-to-body>
      <el-form ref="approveFormRef" :model="approveForm" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="人员" prop="personals"
                          :rules="{ required: true, message: '字段不能为空', trigger: 'blur'}"
            >
              <el-input
                  v-model="approveForm.personals"
                  placeholder="请输入人员ID，多个以英文逗号“,”隔开"
                  maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="approveActionType === 'addsign'">
            <el-form-item label="加签类型" prop="addSignType">
              <el-checkbox v-model="approveForm.addSignType">加签后回到我审批</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审批意见" prop="message"
                          :rules="{ required: true, message: '字段不能为空', trigger: 'blur'}"
            >
              <el-input
                  v-model="approveForm.message"
                  placeholder="请输入审批意见"
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 8 }"
                  maxlength="1024"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitApproveForm('approve')">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 驳回弹窗 -->
    <el-dialog :title="backToStepTitle" v-model="backToStepDialogVisible" width="600px" append-to-body>
      <el-form ref="approveFormRef" :model="approveForm" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="驳回节点" prop="backToStepNode">
              <el-table
                  ref="backNodeTableRef"
                  :data="backNodeList"
                  highlight-current-row
                  style="width: 100%"
                  @current-change="handleBackNodeCurrentChange"
              >
                <el-table-column type="index" width="50"/>
                <el-table-column property="nodeName" label="节点名称" width=""/>
                <el-table-column property="userCode" label="操作人" width="100"/>
                <el-table-column property="endTime" label="操作时间" width="140">
                  <template #default="scope">
                    {{ proxy.parseTime(scope.row.endTime) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审批意见" prop="message"
                          :rules="{ required: true, message: '字段不能为空', trigger: 'blur'}"
            >
              <el-input
                  v-model="approveForm.message"
                  placeholder="请输入审批意见"
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 8 }"
                  maxlength="1024"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitApproveForm('reject')">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="ApproveActions">
import {
  afterAddSign, beforeAddSign, backToStep,
  completeTask, holdTask, stopProcess,
  transferTask, turnTask, claimTask, unClaimTask
} from "@/api/process/process.js";
import {findBackNodesByTaskId} from "@/api/flowable/bpmn/modelInfo.js";
import {parseTime} from "@/utils/ruoyi.js";

const {proxy} = getCurrentInstance();
const emit = defineEmits(["approveSuccess"]);
const loading = ref(false);
const approveActionType = ref('');
const backNodeList = ref([]);

const props = defineProps({
  procInstId: undefined,
  taskId: undefined,
});

const data = reactive({
  form: {message: ''},
  approveForm: {}
});

const approveDialogVisible = ref(false);
const approveTitle = ref('');

const backToStepDialogVisible = ref(false);
const backToStepTitle = ref('');
const currentBackNodeRow = ref()

const {form, approveForm} = toRefs(data);

function onApprove(action) {
  switch (action) {
    case 'approve':
      approve();
      break;
    case 'addsign':
      addsign();
      break;
    case 'hold':
      hold();
      break;
    case 'turn_do':
      turnDo();
      break;
    case 'claim':
      claim();
      break;
    case 'unClaim':
      unClaim();
      break;
    case 'stop':
      stop();
      break;
    case 'turn_read':
      turnRead();
      break;
    case 'reject':
      reject();
      break;
  }
}

/**
 * 组装审批参数
 * @returns {{procInstId, taskId: *}}
 */
function genApproveParams() {
  return {
    taskId: props.taskId,
    procInstId: props.procInstId,
    message: form.value.message
  };
}

/**
 * 审批
 * @returns {Promise<void>}
 */
async function approve() {
  loading.value = true;
  try {
    const result = await completeTask(genApproveParams('approve'));
    proxy.$modal.msgSuccess(result.msg);
    emit('approveSuccess');
    loading.value = false;
  } catch (e) {
    loading.value = false;
  }
}

watch(() => props.procInstId, procInstId => {
  if (procInstId) {
    form.value = {};
    approveForm.value = {};
  }
}, {immediate: true});

/**
 * 审批
 * @returns {Promise<void>}
 */
async function hold() {
  loading.value = true;
  try {
    const result = await holdTask(genApproveParams('hold'));
    proxy.$modal.msgSuccess(result.msg);
    emit('approveSuccess');
    loading.value = false;
  } catch (e) {
    loading.value = false;
  }
}

/**
 * 签收
 * @returns {Promise<void>}
 */
async function claim() {
  loading.value = true;
  try {
    const result = await claimTask(genApproveParams('claimTask'));
    proxy.$modal.msgSuccess(result.msg);
    emit('approveSuccess');
    loading.value = false;
  } catch (e) {
    loading.value = false;
  }
}

/**
 * 反签收
 * @returns {Promise<void>}
 */
async function unClaim() {
  loading.value = true;
  try {
    const result = await unClaimTask(genApproveParams('claimTask'));
    proxy.$modal.msgSuccess(result.msg);
    emit('approveSuccess');
    loading.value = false;
  } catch (e) {
    loading.value = false;
  }
}

/**
 * 终止
 * @returns {Promise<void>}
 */
async function stop() {
  loading.value = true;
  try {
    const result = await stopProcess(genApproveParams('stop'));
    proxy.$modal.msgSuccess(result.msg);
    emit('approveSuccess');
    loading.value = false;
  } catch (e) {
    loading.value = false;
  }
}

/**
 * 审批
 * @returns {Promise<void>}
 */
async function addsign() {
  approveDialogVisible.value = true;
  approveTitle.value = '加签';
  approveActionType.value = 'addsign'
}

/**
 * 审批
 * @returns {Promise<void>}
 */
async function turnDo() {
  approveDialogVisible.value = true;
  approveTitle.value = '转办';
  approveActionType.value = 'turnDo';
}

/**
 * 审批
 * @returns {Promise<void>}
 */
async function turnRead() {
  approveDialogVisible.value = true;
  approveTitle.value = '转阅';
  approveActionType.value = 'turnRead';
}

/**
 * 驳回
 * @returns {Promise<void>}
 */
async function reject() {
  backToStepDialogVisible.value = true;
  backToStepTitle.value = '驳回';
  const res = findBackNodesByTaskId({taskId: props.taskId});

  backNodeList.value = res.data;
  currentBackNodeRow.value = undefined;
}

function handleBackNodeCurrentChange(val) {
  currentBackNodeRow.value = val
}

async function submitApproveForm(actionType) {
  if (actionType === 'reject') {
    if (!currentBackNodeRow.value) {
      proxy.$modal.msgError('请选择驳回的节点！');
      return;
    }

    const data = {
      "taskId": props.taskId,
      "processInstanceId": props.procInstId,
      "message": approveForm.value.message,
      "distFlowElementId": currentBackNodeRow.value.nodeId
    }

    proxy.$modal.loading('正在执行...');

    backToStep(data).then(res => {
      proxy.$modal.msgSuccess(res.msg);
      backToStepDialogVisible.value = false;
      currentBackNodeRow.value = undefined;
      emit('approveSuccess');
    }).catch(e=>{
      proxy.$modal.closeLoading();
    });


  } else if (actionType === 'approve') {
    await proxy.$refs.approveFormRef.validate();

    const data = {
      "taskId": props.taskId,
      "processInstanceId": props.procInstId,
      "message": approveForm.value.message,
    }

    let result = {};
    try {
      proxy.$modal.loading('正在执行...');
      if (approveActionType.value === 'addsign') {
        // approveForm.value.addSignType true 后加签
        if (approveForm.value.addSignType) {
          data.signPersonals = approveForm.value.personals.split(',').map(item => item.trim());
          result = await afterAddSign(data);
        } else {
          data.signPersonals = approveForm.value.personals.split(',').map(item => item.trim());
          result = await beforeAddSign(data);
        }
      } else if (approveActionType.value === 'turnDo') {
        data.turnToUserId = approveForm.value.personals;
        result = await turnTask(data);

      } else if (approveActionType.value === 'turnRead') {
        data.transferToUserNos = approveForm.value.personals.split(',').map(item => item.trim());
        result = await transferTask(data);
      }
      proxy.$modal.msgSuccess(result.msg || '操作成功！');
      approveDialogVisible.value = false;
      proxy.$modal.closeLoading();
      proxy.resetForm("approveFormRef");
      emit('approveSuccess');
    } catch (e) {
      proxy.$modal.closeLoading();
    }
  }
}

function cancel() {
  approveDialogVisible.value = false;
  backToStepDialogVisible.value = false;
}

</script>

<style lang="scss">
.action-btns {
  .el-form-item__content {
    .el-button {
      margin-bottom: 10px;
      margin-left: 0;
      margin-right: 10px;
    }
  }
}
</style>
